//
//  ViewController.m
//  SoundPlayer
//
//  Created by niit on 16/4/5.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "ViewController.h"

#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()
{
    // 定义一个系统声音ID
    SystemSoundID soundID;
}
@property (weak, nonatomic) IBOutlet UILabel *infoLabel;
@property (weak, nonatomic) IBOutlet UISlider *slider;

@property (nonatomic,strong) AVAudioPlayer *player;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 播放短声音(小于5s)
- (IBAction)playSystemSound:(id)sender
{
    if(soundID == 0)
    {
        // 注册这个声音
        NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"AlertChordStroke" withExtension:@"wav"];
        
        // NSURL(Foundation OC语言) -> CFURLRef (CoreFoundation C语言)
        
        // 注册系统段声音
        AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(fileURL), &soundID);
    }
    // 播放
    AudioServicesPlaySystemSound(soundID);
    
}

// 震动
- (IBAction)vibrate:(id)sender
{
    // 播放特殊的声音ID kSystemSoundID_Vibrate
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

#pragma mark - 播放长声音

// 播放
- (IBAction)play:(id)sender {
    
    NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"ワルキューレ - いけないボーダーライン" withExtension:@"mp3"];
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
    
    self.slider.minimumValue = 0;
    self.slider.maximumValue = self.player.duration;// 时长
    [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateInfo) userInfo:nil repeats:YES];
    self.player.numberOfLoops = -1;//一直循环
    
    //后台播放
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
//    [self.player prepareToPlay];  //??
    
    
    [self.player play];
   


    
}

// 停止
- (IBAction)stop:(id)sender
{
    [self.player stop];
}

// 更新信息
- (void)updateInfo
{
    self.slider.value = self.player.currentTime;
    self.infoLabel.text = [NSString stringWithFormat:@"%.1f/%.1f",self.player.currentTime,self.player.duration];// 练习: 转换成分:秒格式 04:00 
}

// 修改当前播放时间
- (IBAction)sliderChanged:(id)sender
{
    self.player.currentTime = self.slider.value;
}


@end
